package com.pinda.interceptor;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import com.pinda.common.CommonClass;
import com.pinda.dto.returndto.R;
import com.pinda.utils.InfoThreadLocal;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

public class LoginInfoInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("token");
        if (StrUtil.isNotEmpty(token)) {
            //验证token
            boolean result = JWTUtil.verify(token, CommonClass.TOKEN_KEY.getBytes());
            if (result) {
                JWT jwt = JWTUtil.parseToken(token);

                Object id = jwt.getPayload("id");
                Object orgId = jwt.getPayload("orgId");
                if (ObjectUtil.isAllNotEmpty(id,orgId)) {
                    Map<String, Long> map = new HashMap<>();
                    map.put("id", Long.valueOf(id+""));
                    map.put("orgId", Long.valueOf(orgId+""));
                    InfoThreadLocal.setInfo(map);
                    return true;
                }
            }
        }
        R<Object> r = R.error("NOAUTH");
        r.setFlag(false);
        String str = JSONUtil.toJsonStr(r);
        response.setStatus(401);
        response.getWriter().write(str);
        return false;

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        InfoThreadLocal.remove();
    }
}
